<?php

class user_settings extends CI_model {
	
	/**
	 * Function index
	 */
	public function index() {
		// construct the parent
		parent::__construct();
	}
	
	
	/**
	 * Function to retrieve the userdata of the given user
	 *
	 * @var mixed $username | false
	 */
	public function get_userdata($username = null) {
		// check if username not is null
		if ($username === null)
			return false;
		
		// get the userdata from the database
		$this->db->select('first_name, last_name, username, email, telephone');
		$this->db->where('username', $username);
		$userdata = $this->db->get('users');
		
		return ($userdata) ? $userdata->result()[0] : false;
	}
	
	
	/**
	 * Function to update the userdata
	 * 
	 * @param string $username
	 * 
	 * @return boolean $update
	 */
	public function save_userdata($username = null) {
		if ($username == null)
			return false;
		
		try {
			// create database query by looping through all input posts
			foreach($this->input->post() as $post => $value) {
				$this->db->set($post, $value);
			}
			
			// make sure the data will be updated for the right user
			$this->db->where('username', $username);
			// update the userdata
			$update = $this->db->update('users');
			
			if (!$update) {
			  throw new Exception('Error in query');
			  return false;
			}
			
		} catch(Exception $e) {}
		
		return (bool) $update;
	}
	
	
	/** 
	 * Function to retrieve the last_login time
	 * 
	 * @return mixed $last_login | false
	 */
	public function get_last_login() {
		// get the username
		$username = $this->username;
		
		// get the last_login value from the database
		$this->db->select('last_login');
		$this->db->where('username', $username);
		$last_login = $this->get('users');
		
		return ($last_login) ? $last_login : false;
	}
}